<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

if (!function_exists('config')) {
  function config($keyStr) {
    $config = require __DIR__ . '/../configs/config.php';
    $keys = explode(".", $keyStr);

    $target = null;
    foreach ($keys as $k) {
      if (! $target) {
        if (! isset($config[$k])) {
          return null;
        }

        $target = $config[$k];
        continue;
      }

      if (! isset($target[$k])) {
        return null;
      }

      $target = $target[$k];
    }

    return $target;
  }
}

if (!function_exists('send_error_email')) {
  function send_error_email($errMsg, $log) {
    $mail = new PHPMailer(true);

    try {
      //Server settings
      $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      //Enable verbose debug output
      $mail->isSMTP();                                            //Send using SMTP
      $mail->Host       = 'smtp.sina.com';                     //Set the SMTP server to send through
      $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
      $mail->Username   = 'lfz611@sina.com';                     //SMTP username
      $mail->Password   = '3e77cdb2c40490a9';                               //SMTP password
      $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
      $mail->Port       = 465;                                  //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
      $mail->CharSet    = 'utf-8';
      //Recipients
      $mail->setFrom('lfz611@sina.com', 'JasonLiang');
      $mail->addAddress('56722694@qq.com', 'JasonLiang');     //Add a recipient
      $mail->addAddress('1322335854@qq.com', 'Almasgeek');     //Add a recipient
      $mail->addReplyTo('lfz611@sina.com', 'JasonLiang');

      //Content
      $mail->isHTML(true);                                  //Set email format to HTML
      $mail->Subject = 'elastic同步服务器故障！';
      $mail->Body    = $errMsg;
      // $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

      $mail->send();
      echo 'error Message has been sent';
    } catch (Exception $e) {
      echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
      $log->error('mailer send exception: ' . $mail->ErrorInfo);
    }
  }
}

if (!function_exists('build_tree')) {
  function build_tree($data, $parentId = 0) {
    $tree = [];

    foreach ($data as $item) {
      if ($item['parent_id'] == $parentId) {
        $children = build_tree($data, $item['id']);
        if (!empty($children)) {
          $item['children'] = $children;
        }
        $tree[] = $item;
      }
    }

    return $tree;
  }
}